package com.hefei.edu.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hefei.edu.entity.Subject;
import com.hefei.edu.excel.SubjectExcel;
import com.hefei.edu.listener.SubjectExcelListener;
import com.hefei.edu.mapper.SubjectMapper;
import com.hefei.edu.service.ISubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hefei.edu.vo.Tree;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author caizhengjun
 * @since 2021-03-04
 */
@Service
public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, Subject> implements ISubjectService {

    @Autowired
    private SubjectMapper subjectMapper;

    @Override
    public void saveExcel(MultipartFile file) {

        InputStream is = null;
        try {
            is = file.getInputStream();

            EasyExcel.read(is, SubjectExcel.class, new SubjectExcelListener(subjectMapper))
                    .sheet()
                    .doRead();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void writeExcel() {

        List<SubjectExcel> arrayList = new ArrayList<>();

        for (int i = 0; i < 10; i++) {
            SubjectExcel excel = new SubjectExcel();
            excel.setSub1("前端");
            excel.setSub2("Html");
            excel.setSub3("Js");
            arrayList.add(excel);
        }

        EasyExcel.write("write.xlsx", SubjectExcel.class).sheet("学生列表").doWrite(arrayList);
    }

    @Override
    public List<Tree> tree() {
        return findNode("0");
    }

    private List<Tree> findNode(String id) {

        List<Tree> trees = new ArrayList<>();
        QueryWrapper<Subject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", id);

        List<Subject> subjects = this.subjectMapper.selectList(queryWrapper);

        if (CollectionUtils.isEmpty(subjects)) {
            return null;
        }

        for (Subject subject : subjects) {

            String parentId = subject.getId();
            Tree tree = new Tree();
            tree.setId(subject.getId());
            tree.setLabel(subject.getTitle());
            tree.setChildren(findNode(parentId));
            trees.add(tree);
        }
        return trees;
    }
}
